//
//  DemoTimer.swift
//  swiftDemo
//
//  Created by JIENING ZHANG on 2022/11/27.
//  Copyright © 2022 lovivid. All rights reserved.
//

import UIKit

class DemoTimer: NSObject {
    //private var timer: Timer?
    private var actionCallCount = 0;
    
    // selector 指定定时器每次计时结束要执行的方法，必须为 @objc 的函数对象
    @objc func actionWithTimer(_ tr:Timer?) {
        self.actionCallCount += 1;
        DemoDateTime.logTs("actionWithTimer, actionCallCount=\(self.actionCallCount)", "ms");
        if self.actionCallCount > 3 {
            
            if (tr?.userInfo) == nil {
                self.delayByScheduledTimer();
            }
            if tr?.userInfo is Array<Any> {
                self.delayByGCDTimer();
            }
            
            
            tr?.invalidate();
        }
    }
    
    func delayByGCD() {
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500), execute: {
            DemoDateTime.logTs("DispatchQueue.main.asyncAfter, actionCallCount=\(self.actionCallCount)", "ms", true);
            DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(500), execute: {
                DemoDateTime.logTs("DispatchQueue.global().asyncAfter, actionCallCount=\(self.actionCallCount)", "ms", true);
            });
        });
    }
    
    func delayByGCDTimer() {
        self.actionCallCount = 0;
        let gcdTimer = DispatchSource.makeTimerSource();
        gcdTimer.setEventHandler() {
            self.actionCallCount += 1;
            DemoDateTime.logTs("gcdTimer EventHandler, actionCallCount=\(self.actionCallCount)", "ms");
            if self.actionCallCount > 3 {
                gcdTimer.cancel();
            }
        }
        gcdTimer.setCancelHandler() {
            DemoDateTime.logTs("gcdTimer CancelHandler, actionCallCount=\(self.actionCallCount)", "ms");
            self.delayByGCD();
        }
        
        gcdTimer.schedule(deadline: .now() + .milliseconds(100), repeating: .milliseconds(500));
        gcdTimer.resume()
    }
    
    func delayByScheduledTimer() {
        self.actionCallCount = 0;
        // 创建 Timer 对象，并且以默认的运行模式添加到当前的 RunLoop 中
        Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.actionWithTimer(_:)), userInfo:[],  repeats: true);
    }
    
    func delayByTimer() {
        // 类方法初始化 Timer 对象，将对象手动添加到指定 RunLoop 中执行
        let timer = Timer(timeInterval: 0.5, target: self, selector: #selector(self.actionWithTimer(_:)), userInfo:nil, repeats: true);
        RunLoop.main.add(timer, forMode: .common);
        
    }
    
    class func demoLogic() {
        // https://zhuanlan.zhihu.com/p/58416033
        let demo = DemoTimer();
        demo.delayByTimer();
    }
}
